
import requests

from tkinter import *
from MY_GUI import MY_GUI
from urllib3.exceptions import MaxRetryError

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.3'
}

pre_target_url = 'https://stickershop.line-scdn.net/stickershop/v1/sticker/{}/android/sticker.png'


class myStdout():  # 重定向类
    def __init__(self):
        # 将其备份
        self.stdoutbak = sys.stdout
        self.stderrbak = sys.stderr
        # 重定向
        sys.stdout = self
        sys.stderr = self

    def write(self, info):
        # info信息即标准输出sys.stdout和sys.stderr接收到的输出信息
        Crawer.result.insert('end', info)  # 在多行文本控件最后一行插入print信息
        Crawer.result.update()  # 更新显示的文本，不加这句插入的信息无法显示
        Crawer.result.see(END)  # 始终显示最后一行，不加这句，当文本溢出控件最后一行时，不会自动显示最后一行

    def restoreStd(self):
        # 恢复标准输出
        sys.stdout = self.stdoutbak
        sys.stderr = self.stderrbak


def load_bytes_test() -> str:
    """
    read saw file by name
    :return: string which full urls in
    """
    with open('./b.txt', 'r') as f:
        return f.readline()


def get_str_from_url(url: str) -> str:
    """

    :param url: web url
    :return: saw string to be marched
    """
    response = requests.get(url, headers=header)
    return str(response.content)


def tin_url_list(url_list: list) -> (list, int, int):
    """
    This function will be refactor in next
    :param url_list: full pic url
    :return: formatted data
    """
    temp = []
    # first = 0
    pattern4findfirst = r'/\d+'

    for li in url_list:
        if li not in temp:
            temp.append(li)
    t = re.findall(pattern4findfirst, url_list[0])
    first = int(t[0][1:])
    # print(url_list[0].split(str(first)))
    print('Have found {} pictures'.format(len(temp)))

    return temp, first, len(temp)


def get_from_num(num) -> bool:
    """

    :param num: number of pic
    :return: flag shows this pic if saved successfully
    """
    target_url = pre_target_url.format(str(num))
    try:
        pic_data = requests.get(target_url, headers=header)
        with open('./arc/{}.png'.format(str(num)), 'wb+') as pic_file:
            pic_file.write(pic_data.content)
            print('pic_{}.png have been saved!'.format(str(num)))
            pic_data.close()
        return True
    except TimeoutError as ex:
        return False
    except MaxRetryError as ex:
        return False
    except requests.exceptions.ConnectionError as ex:
        return False


patten = r'https://stickershop.line-scdn.net/stickershop/v1/sticker/\d+/android/sticker.png'
target_url = 'https://store.line.me/stickershop/product/14308849/zh-Hans'

mystd = myStdout()  # 实例化重定向类
init_window = Tk()  # 实例化出一个父窗口
Crawer = MY_GUI(init_window)
# 设置根窗口默认属性
Crawer.set_init_window()

# 下面的代码或许写到按钮绑定事件里面？
# res = re.findall(patten, get_str_from_url(target_url))
# url_list, first, length = tin_url_list(res)
#
# if not os.path.exists('arc'):
#     os.mkdir('arc')
# for i in range(first, first + length):
#     tr = threading.Thread(target=get_from_num, args=(i,))
#     tr.start()

# from MY_GUI import click_all_pic
# click_all_pic()



init_window.mainloop()  # 父窗口进入事件循环，可以理解为保持窗口运行，否则界面不展示
mystd.restoreStd()  # 恢复标准输出




# def click_all_pic():
#     res = re.findall(patten, get_str_from_url(target_url))
#     url_list, first, length = tin_url_list(res)
#
#     if not os.path.exists('arc'):
#         os.mkdir('arc')
#     for i in range(first, first + length):
#         tr = threading.Thread(target=get_from_num, args=(i,))
#         tr.start()
